package com.entrogy.AccessToken;

import com.Sinewecology.SendMessage.SendMsgThread;
import com.entrogy.bean.GongZhongHaoEntity;
import com.entrogy.dao.GongZhongHaoMapper;
import com.entrogy.dao.MessageMapper;
import com.entrogy.utils.RedisUtil;
import com.entrogy.utils.RedissonManager;
import com.entrogy.utils.StudentRecordUtil;
import com.entrogy.utils.constants.Constants;
import org.redisson.api.RLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author xlr
 */
@Component
public class AccessTokenUpdate implements CommandLineRunner {

	private static Logger logger = LoggerFactory.getLogger(AccessTokenUpdate.class);
	boolean getLock = false;

	private RedisUtil redisUtil = new RedisUtil();
	@Autowired
	private RedissonManager redissonManager;
	@Autowired
	private GongZhongHaoMapper gongZhongHaoMapper;
	@Autowired
	private MessageMapper messageMapper;

	public void getWeixinToken() {
		logger.info("第一次读取AccessToken!");
		while (true) {
			RLock lock = redissonManager.getRedisson().getLock(Constants.WEIXIN_TOMKEN_TASK_LOCK);
			try {
				if(getLock = lock.tryLock(0,5, TimeUnit.SECONDS)) {
					//获取多个公众号
					List<GongZhongHaoEntity> gongZhongHaoEntities = gongZhongHaoMapper.getGongZhongHaoList();
					for (GongZhongHaoEntity gongZhongHaoEntity : gongZhongHaoEntities) {
//						String tokenStr = (String) redisUtil.get(gongZhongHaoEntity.getUsername());//获取WXTOKEN
//						if (StrUtils.isNullOrEmpty(tokenStr)) {
						logger.info("更新AccessToken!");
						WX_TokenUtil.getWXToken(gongZhongHaoEntity);
						Thread.sleep(5000);//睡一会在关闭锁

//						}
					}//所有公众号的TOKEN已获取完成
					if (getLock) {
						lock.unlock();
						logger.info("获取微信TOKEN的时候释放锁");
					}
					Thread.sleep((7200 - 200) * 1000);//休息一会
				} else {
					logger.info("老弟你没有获取到微信TOKEN锁哟");
				}
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("获取微信TOKEN的时候获取锁异常",e);
				logger.error("@@@@@@@@@@@@@@@@@@@@@@@@********8获取微信TOKEN出错，请紧急处理****@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
			}finally {
				if (getLock) {
					lock.unlock();
//					logger.info("获取微信TOKEN的时候释放锁");
				}
			}
		}
	}

	@Override
	public void run(String... args) throws Exception {
		new StudentRecordUtil().start();
		new SendMsgThread(messageMapper).start();
//		getWeixinToken();  //TODO ---上线要放开----------------
	}

}
